package com.dlc.shop.seckill.common.listener;

import com.dlc.shop.bean.event.PaySuccessHandleOrderStockEvent;
import com.dlc.shop.bean.model.OrderItem;
import com.dlc.shop.bean.order.PaySuccessOrderOrder;
import com.dlc.shop.common.bo.MultiDecrementBO;
import com.dlc.shop.common.enums.MultiStockEnum;
import com.dlc.shop.seckill.common.model.Seckill;
import com.dlc.shop.seckill.common.service.SeckillCacheManager;
import com.dlc.shop.seckill.common.service.SeckillService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 秒杀成功回调
 * @author LGH
 */
@Component("paySuccessHandleOrderStockListener")
@AllArgsConstructor
public class PaySuccessHandleOrderStockListener {

    private final SeckillService seckillService;
    private final SeckillCacheManager seckillCacheManager;

    /**
     * 更新秒杀状态
     */
    @EventListener(PaySuccessHandleOrderStockEvent.class)
    @Order(PaySuccessOrderOrder.SECKILL)
    public void seckillPaySuccessListener(PaySuccessHandleOrderStockEvent event) {
        com.dlc.shop.bean.model.Order order = event.getOrder();
        OrderItem orderItem = order.getOrderItems().get(0);
        boolean stockCheck = true;
        // 秒杀活动信息（来自缓存）
        Seckill seckill = seckillService.getSeckillById(orderItem.getActivityId());
        // 判断之前秒杀的商品有没有超过限制，-1表示商品不限制秒杀数量
        if (!Objects.equals(seckill.getMaxNum(), -1)) {
            int dbCount = seckillCacheManager.selectNumByUser(seckill.getSeckillId(), order.getUserId());
            if (seckill.getMaxNum() < orderItem.getProdCount() + dbCount) {
                stockCheck = false;
            }
        }
        // 用户没有达到购买上限，且秒杀商品还有库存，则购买成功
        boolean deductStock = true;
        try {
            MultiDecrementBO multiDecrementBO = new MultiDecrementBO(MultiStockEnum.SECKILL, orderItem.getUserId(), orderItem.getOrderNumber(),
                    orderItem.getActivityId(), orderItem.getSkuId(), orderItem.getProdCount(), seckill.getMaxNum(), null);
            multiDecrementBO.setStockPointId(orderItem.getStockPointId());
            multiDecrementBO.setProdName(orderItem.getProdName());
            seckillCacheManager.decrSeckillSkuStocks(multiDecrementBO);
        } catch (Exception e) {
            deductStock = false;
        }
        if(deductStock && stockCheck){
            event.getSuccessOrderList().add(order);
        }else {
            event.getRefundOrderList().add(order);
        }
    }
}
